/*
 * Copyright (C) 2015 Square, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { ConnectionSpec } from "../ConnectionSpec"
import {
  CertificateException,
  InterruptedIOException,
  ProtocolException,
  SSLException,
  SSLHandshakeException,
  SSLPeerUnverifiedException,
  UnknownServiceException
} from "../Error/error"
import { SSLSocket } from "../Socket/SSLSocket"

/**
 * Handles the connection spec fallback strategy: When a secure socket connection fails due to a
 * handshake / protocol problem the connection may be retried with different protocols. Instances
 * are stateful and should be created and used for a single connection attempt.
 */
export class ConnectionSpecSelector{
  private connectionSpecs: Array<ConnectionSpec>
  constructor(connectionSpecs: Array<ConnectionSpec>) {
    this.connectionSpecs = connectionSpecs
  }

  private nextModeIndex: number = 0
  private isFallbackPossible: boolean = false
  private isFallback: boolean = false

  /**
   * Configures the supplied [SSLSocket] to connect to the specified host using an appropriate
   * [ConnectionSpec]. Returns the chosen [ConnectionSpec], never null.
   *
   * @throws IOException if the socket does not support any of the TLS modes available
   */
  // @Throws(IOException::class)
  configureSecureSocket(sslSocket: SSLSocket): ConnectionSpec {
    let tlsConfiguration: ConnectionSpec | null = null
    for (let i = this.nextModeIndex; i < this.connectionSpecs.length; i++){
      let connectionSpec = this.connectionSpecs[i]
      if (connectionSpec.isCompatible(sslSocket)){
        tlsConfiguration = connectionSpec
        this.nextModeIndex = i + 1
        break
      }
    }

    if (tlsConfiguration === null || tlsConfiguration === undefined) {
      // This may be the first time a connection has been attempted and the socket does not support
      // any the required protocols, or it may be a retry (but this socket supports fewer protocols
      // than was suggested by a prior socket).
      throw new UnknownServiceException("UnknownService: "+ `Unable to find acceptable protocols. isFallback=${this.isFallback},` +'\n' +
        ` modes=${this.connectionSpecs},` +'\n' +
        ` supported protocols=$sslSocket.enabledProtocols!!.contentToString()`)

    }

    this.isFallbackPossible = this.isFallbackPossibleCheck(sslSocket)

    tlsConfiguration.apply(sslSocket, this.isFallback)

    return tlsConfiguration
  }

  /**
   * Reports a failure to complete a connection. Determines the next [ConnectionSpec] to try,
   * if any.
   *
   * @return true if the connection should be retried using [configureSecureSocket].
   */
  connectionFailed(e: Error): boolean {
    // Any future attempt to connect using this strategy will be a fallback attempt.
    this.isFallback = true

    if (!this.isFallbackPossible) {
      return false
    }

    // If there was a protocol problem, don't recover.
    if (e instanceof ProtocolException) {
      return false
    }

    // If there was an interruption or timeout (SocketTimeoutException), don't recover.
    // For the socket connect timeout case we do not try the same host with a different
    // ConnectionSpec: we assume it is unreachable.
    if (e instanceof InterruptedIOException) {
      return false
    }

    // If the problem was a CertificateException from the X509TrustManager, do not retry.
    if (e instanceof SSLHandshakeException && e.cause instanceof CertificateException) {
      return false
    }

    // e.g. a certificate pinning error.
    if (e instanceof SSLPeerUnverifiedException) {
      return false
    }

    // Retry for all other SSL failures.
    if (e instanceof SSLException) {
      return true
    }

    return false
  }

  /**
   * Returns true if any later [ConnectionSpec] in the fallback strategy looks possible based on the
   * supplied [SSLSocket]. It assumes that a future socket will have the same capabilities as the
   * supplied socket.
   */
  private isFallbackPossibleCheck(socket: SSLSocket): boolean {
    for (let i = this.nextModeIndex; i < this.connectionSpecs.length; i++){
      if (this.connectionSpecs[i].isCompatible(socket)) {
        return true
      }
    }
    return false
  }
}
